package com.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
 * @Author: lizehui
 * @Description:
 * @Date: 2022/11/02/16:24
 */
@Configuration
public class RedisConfig {
    @Bean
    public StringRedisSerializer stingRedisSerializer() {
        return new StringRedisSerializer();
    }

    /**
     * redisTemplate 序列化默认使用的jdk Serializable, 存储二进制字节码, 所以自定义序列化类
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory,StringRedisSerializer stingRedisSerializer) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        // 值采用json序列化
        template.setValueSerializer(stingRedisSerializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(stingRedisSerializer);

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(stingRedisSerializer);
        template.setHashValueSerializer(stingRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
}
